<?php

/**
 * Creating HTML to visualizise current data
 * 
 * @author Aldis Rameika
 */
class CurrentDataDesign {
    /*
     * Fills current data spreadsheets
     */

    public static function show_current_data($subdivisions, $administration, $is_subs, $dates, $historical) {
        MainDesign::h1("Vienos paraiškos suadministravimo laikas");
        ?>
        <div id="appGrid" style="width:560px;;height:500px;"></div>
        <div id="appGridButtons"></div>
        <input type="button" id="editApp" value="Išsaugoti pakeitimus" onclick="saveAppData()"/>
        <input type="button" id="notSaveApp" value="Nesaugoti pakeitimų" onclick="unsetAppData()"/>

        <? MainDesign::h1("Naudojamos Informacinės sistemos"); ?>
        <div id="usedGrid" style="width:560px;height:276px;"></div>
        <input type="button" id="editUsed" value="Išsaugoti pakeitimus" onclick="saveUsedData()"/>
        <input type="button" id="notSaveUsed" value="Nesaugoti pakeitimų" onclick="unsetUsedData()"/>

        <? MainDesign::h1("Gauta paraiškų"); ?>
        <div id="receivedGrid" style="width:560px;height:500px;"></div>
        <input type="button" id="editReceived" value="Išsaugoti pakeitimus" onclick="saveReceivedData()"/>
        <input type="button" id="notSaveReceived" value="Nesaugoti pakeitimų" onclick="unsetReceivedData()"/>

        <script>
            var appGrid;
            var appColumns;
            var appData;
            var backupAppData;
                                                                                                                                                                  
            var usedGrid;
            var usedColumns;
            var usedData;
            var backupUsedData;

            var receivedGrid;
            var receivedColumns;
            var receivedData;
            var backupReceivedData;
                                                                                                    
            var options = [{multiSelect: false}];
                                                                                                                                                                                                                                            
            window.onload = function () {
                function requiredFieldValidator(value) {
                    if (value == null || value == undefined || !value.length)
                        return {valid:false, msg:"This is a required field"};
                    else
                        return {valid:true, msg:null};
                }
                                                                                                        
                appData = <? echo self::generate_app_grid_data($administration); ?>;
                backupAppData = <? echo self::generate_app_grid_data($administration); ?>;
                test = <? echo self::generate_app_grid_data($administration); ?>;
                appColumns = <? echo self::generate_columns("Priemonė", $subdivisions); ?>;
                                                                                                
                appGrid = new Slick.Grid("#appGrid", appData, appColumns, options);
                appGrid.setSelectionModel(new Slick.CellSelectionModel(options));
                                                                                                                                                                                                                                                                        
                usedData = <? echo self::generate_used_grid_data($is_subs); ?>;
                backupUsedData = <? echo self::generate_used_grid_data($is_subs); ?>;
                usedColumns = <? echo self::generate_columns("IS", $subdivisions, true); ?>;
                                                                                                                                                                                                                                                                        
                usedGrid = new Slick.Grid("#usedGrid", usedData, usedColumns, options);
                usedGrid.setSelectionModel(new Slick.CellSelectionModel());
                                                                                                                                                                                                                                        
                receivedData = <? echo self::generate_received_grid_data($historical); ?>;
                backupReceivedData = <? echo self::generate_received_grid_data($historical); ?>;
                receivedColumns = <? echo self::generate_received_columns("Priemonė", $dates); ?>;
                                                                                                                                                                
                receivedGrid = new Slick.Grid("#receivedGrid", receivedData, receivedColumns, options);
                receivedGrid.setSelectionModel(new Slick.CellSelectionModel());
            }
                                                                                    
            function saveBackUp(type) {
                if (type == "appData") {
                    backupAppData = createBackUp(appGrid.getData());
                } else if (type == "usedData") {
                    backupUsedData = createBackUp(usedGrid.getData());
                } else if (type == "receivedData") {
                    backupReceivedData = createBackUp(receivedGrid.getData());
                }
            }
                                    
            function createBackUp(gridData) {
                var newBackup = [];
                var gridDataLength = gridData.length;
                for (var i = 0; i < gridDataLength; i++) {
                    newBackup[i] = {};
                    var properties = {};
                    for (var property in gridData[i]) {
                        if (gridData[i][property] != "unchecked" && gridData[i][property] != "undefined") {
                            properties[property] = gridData[i][property] + "";
                        }
                    }
                    newBackup[i] = properties;
                }
                return newBackup;
            }
                                                                                    
            function getBackUp(type) {
                var backupData = [];
                if (type == "appData") {
                    backupData = createBackUp(backupAppData);
                } else if (type == "usedData") {
                    backupData = createBackUp(backupUsedData);
                } else if (type == "receivedData") {
                    backupData = createBackUp(backupReceivedData);
                }
                return backupData;
            }
                                                                                                                                                            
            function unsetAppData() {
                appGrid.setData(getBackUp("appData"), false);
                appGrid.render();
            }
                                                                                                                                            
            function unsetUsedData() {                             
                usedGrid.setData(getBackUp("usedData"), false);
                usedGrid.render();
            }
                                                                                                                                            
            function unsetReceivedData() {                              
                receivedGrid.setData(getBackUp("receivedData"), false);
                receivedGrid.render();
            }
                                                                                                                                                                                                    
            function saveAppData() {
                if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp=new XMLHttpRequest();
                } else { // code for IE6, IE5
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                                                                                                                                                        
                var params = 'option=saveApp&params=' + getParams(appGrid.getData());                                        
                params += '&params2=' + getParams(getBackUp("appData"));
                                                                
                xmlhttp.open("POST", "GUI/Tabs/CurrentData/editDB.php", true)
                xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
                xmlhttp.setRequestHeader("Content-length", params.length);
                xmlhttp.send(params);
                saveBackUp("appData");
            }
                                                                                                                                                                                                    
            function saveUsedData() {
                if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp=new XMLHttpRequest();
                } else { // code for IE6, IE5
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                
                var params = 'option=saveUsed&params=' + getParams(usedGrid.getData());                 
                params += '&params2=' + getParams(getBackUp("usedData"));
                                                                                                                                                        
                xmlhttp.open("POST", "GUI/Tabs/CurrentData/editDB.php", true)
                xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
                xmlhttp.setRequestHeader("Content-length", params.length);
                xmlhttp.send(params);
                saveBackUp("usedData");
            }
                                                                                                                                                                                                    
            function saveReceivedData() {
                if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp=new XMLHttpRequest();
                } else { // code for IE6, IE5
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }

                var params = 'option=saveReceived&params=' + getParams(receivedGrid.getData());                       
                params += '&params2=' + getParams(getBackUp("receivedData"));
                                                                                                                                                        
                xmlhttp.open("POST", "GUI/Tabs/CurrentData/editDB.php", true)
                xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
                xmlhttp.setRequestHeader("Content-length", params.length);
                xmlhttp.send(params);
                saveBackUp("receivedData");
            }
                                                    
            function getParams(gridData) {
                var params = '';
                var gridDataLength = gridData.length;
                for (var i = 0; i < gridDataLength; i++) {
                    for (var property in gridData[i]) {
                        params += property + ':' + gridData[i][property] + ',';
                    }
                    params += "::"
                }
                return params;
            }
        </script>
        <?
    }

    /*
     * Generating spreadsheet columns
     */

    private static function generate_columns($first_header, $subdivisions, $is_bool = false) {
        $generated_columns = '[
            {id:"type", name:"' . $first_header . '", field:"type", width:98,
            cssClass:"cell-title", editor:TextCellEditor, validator:requiredFieldValidator},
            ';

        foreach ($subdivisions["CODE"] as $subdivision => $title) {
            $generated_columns .= '{id:"' . $title . '", name:"' . $title . '", field:"' . $title . '", width:37,
            editor:TextCellEditor, cssClass:"spreadsheet-cell"';
            if ($is_bool) {
                $generated_columns .= ", formatter:BoolCellFormatter, editor:YesNoCheckboxCellEditor},";
            } else {
                $generated_columns .= "},";
            }
        }

        $generated_columns = substr_replace($generated_columns, "]", -1);
        return $generated_columns;
    }

    /*
     * Generating received spreadsheet columns
     */

    private static function generate_received_columns($first_header, $dates) {
        $generated_columns = '[
            {id:"type", name:"' . $first_header . '", field:"type", width:98,
            cssClass:"cell-title", editor:TextCellEditor, validator:requiredFieldValidator},
            ';

        foreach ($dates as $date => $is_forecast) {
            $generated_columns .= '{id:"' . $date . '", name:"' . substr($date, 0, 7) . '", field:"' . $date . '", width:50,
            editor:TextCellEditor, cssClass:"spreadsheet-cell"},';
        }

        $generated_columns = substr_replace($generated_columns, "]", -1);
        return $generated_columns;
    }

    /*
     * Generating spreadsheet data by measure administration
     */

    private static function generate_app_grid_data($administrations) {
        $generated_data = "[
            ";

        $entrys = count($administrations["MEASURE_CODE"]);
        $current_measure = "";
        if ($entrys != 0) {
            $current_measure = $administrations["MEASURE_CODE"][0];
            $generated_data .= "{ type: '" . $current_measure . "', ";
        }

        for ($i = 0; $i < $entrys; $i++) {
            if ($current_measure == $administrations["MEASURE_CODE"][$i]) {
                $generated_data .= $administrations["SUBDIVISION_CODE"][$i] . ": " . $administrations["TIME"][$i] . ",";
            } else {
                $generated_data = substr_replace($generated_data, "},", -1);
                $current_measure = $administrations["MEASURE_CODE"][$i];
                $generated_data .= "{ type: '" . $current_measure . "',";
                $generated_data .= $administrations["SUBDIVISION_CODE"][$i] . ": " . $administrations["TIME"][$i] . ",";
            }
        }

        $generated_data = substr_replace($generated_data, "}]", -1);
        return $generated_data;
    }

    /*
     * Generating spreadsheet data by used IS'es by subdivision
     */

    private static function generate_used_grid_data($is_subs) {
        $generated_data = "[
            ";

        $entrys = count($is_subs["IS_CODE"]);
        $current_is = "";
        if ($entrys != 0) {
            $current_is = $is_subs["IS_CODE"][0];
            $generated_data .= "{ type: '" . $current_is . "', ";
        }

        for ($i = 0; $i < $entrys; $i++) {
            if ($current_is == $is_subs["IS_CODE"][$i]) {
                $generated_data .= $is_subs["SUBDIVISION_CODE"][$i] . ": " . true . ",";
            } else {
                $generated_data = substr_replace($generated_data, "},", -1);
                $current_is = $is_subs["IS_CODE"][$i];
                $generated_data .= "{ type: '" . $current_is . "',";
                $generated_data .= $is_subs["SUBDIVISION_CODE"][$i] . ": " . true . ",";
            }
        }

        $generated_data = substr_replace($generated_data, "}]", -1);
        return $generated_data;
    }

    /*
     * Generating spreadsheet data by used IS'es by subdivision
     */

    private static function generate_received_grid_data($historical) {
        $generated_data = "[
            ";

        $entrys = count($historical);

        foreach ($historical as $measure => $data) {
            $generated_data .= "{ type: '" . $measure . "'";
            foreach ($data as $date => $received) {
                $generated_data .= ",'" . $date . "': " . $received;
            }
            $generated_data .= "},";
        }

        $generated_data = substr_replace($generated_data, "]", -1);
        return $generated_data;
    }

}
?>
